package com.jwthhealth_pub.wristband.presenter;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.content.Intent;
import android.util.Log;

import com.jwthhealth_pub.app.App;
import com.jwthhealth_pub.common.base.BaseResp;
import com.jwthhealth_pub.old.api.ApiHelper;
import com.jwthhealth_pub.old.common.Constant;
import com.jwthhealth_pub.old.sign.model.LoginModel;
import com.jwthhealth_pub.utils.Contas;
import com.jwthhealth_pub.wristband.broadcast.WristBandReceiver;
import com.jwthhealth_pub.wristband.main.model.WristBandSettingModule;
import com.jwthhealth_pub.wristband.manager.BLEManager;
import com.jwthhealth_pub.wristband.manager.WristbandManager;
import com.jwthhealth_pub.wristband.service.WristBandService;
import com.jwthhealth_pub.wristband.service.model.BloodHeartPastModule;
import com.jwthhealth_pub.wristband.service.model.SleepTimeModule;
import com.jwthhealth_pub.wristband.service.model.StepPassDataModule;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.jwthhealth_pub.common.LogUtil.makeLogTag;

/**
 * 蓝牙操作
 * Created by liuzhen on 2017/12/16.
 */

public class IWristBandServicePresenterCompl implements IWristBandServicePresenter.presenter {

    public static final String TAG = makeLogTag(IWristBandServicePresenterCompl.class);

    private final WristBandService mService;
    private BLEManager mBleManager;
    private WristbandManager mWristbandManager;

    public IWristBandServicePresenterCompl(WristBandService service) throws Exception {
        this.mService = service;
        this.mBleManager = new BLEManager(mService);
    }

    @Override
    public void enableBlutTooth() {
        if (!mBleManager.isEnable()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            mService.startActivity(enableBtIntent);
        }
    }

    /**
     * 发送蓝牙手环状态广播
     *
     * @param type 0 不支持蓝牙 1 蓝牙断开
     */
    @Override
    public void sendServiceBrocast(int type) {
        try {
            Intent brocastIntent = new Intent();
            brocastIntent.setAction(Constant.PACKAGENAME);

            switch (type) {
                case 0:
                    brocastIntent.putExtra(Constant.TAG, WristBandReceiver.BLUETOOTH_NOTSUPPORT);
                    break;
                case 1:
                    brocastIntent.putExtra(Constant.TAG, WristBandReceiver.BLUETOOTH_OFF);
                    break;
                default:
                    break;
            }

            mService.sendBroadcast(brocastIntent);
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }

    }

    /**
     * 发送蓝牙手环状态广播
     *
     * @param type  2 即时步数 3 即时心率 4 即使血压 5 血氧
     * @param value value
     */
    @Override
    public void sendServiceBrocast(int type, int value) {

        Intent brocastIntent = new Intent(Constant.PACKAGENAME);
        switch (type) {
            case 2:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_STEP_CHANGED);

                ArrayList<String> stepParam = (ArrayList<String>) WristbandManager.getStepParam(value);

                for (String s : stepParam) {
                    if (s == null) return;
                }

                brocastIntent.putStringArrayListExtra(Constant.WRISTBAND_DATA, stepParam);
                App.mContext.sendBroadcast(brocastIntent);
                break;
            case 5:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_OXYGEN_CHANGED);

                if (value >= 0) {
                    brocastIntent.putExtra(Constant.WRISTBAND_DATA, value + "");
                    App.mContext.sendBroadcast(brocastIntent);
                }
                break;
            case 6:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_FATIFUE_CHANGED);

                if (value >= 0) {
                    brocastIntent.putExtra(Constant.WRISTBAND_DATA, value + "");
//                    Log.d(TAG, "send fatigue");
                    App.mContext.sendBroadcast(brocastIntent);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发送蓝牙手环状态广播
     *
     * @param type   2 即时步数 3 即时心率 4 即使血压
     * @param values value
     */
    @Override
    public void sendServiceBrocast(int type, byte[] values) {

        Intent brocastIntent = new Intent(Constant.PACKAGENAME);
        switch (type) {
            case 3:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_HEART_CHANGED);

                // TODO: 2017/12/26 心律的数值未计算完毕
                byte value = values[1];
                int heartValueSingle = WristbandManager.calc(new byte[]{value});
//
//                for (byte heartValeu : values) {
//                    Log.d(TAG, "heartValeus[i]:" + heartValeu);
//                }
//
//                Log.d(TAG, "value:" + value);

                if (heartValueSingle < 0)
                    return;

                brocastIntent.putExtra(Constant.WRISTBAND_DATA, heartValueSingle + "");
                App.mContext.sendBroadcast(brocastIntent);
            case 4:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_BLOOD_CHANGED);

                byte[] systolicpressures = new byte[]{values[1], values[2]};
                byte[] diastolicpressures = new byte[]{values[3], values[4]};
                byte[] bloodheart = new byte[]{values[7], values[8]};

                int systolicpressuresValue = WristbandManager.calc(systolicpressures);
                int diastolicpressuresValue = WristbandManager.calc(diastolicpressures);
                int heartValue = WristbandManager.calc(bloodheart);

                ArrayList<String> list = new ArrayList<>();
                list.add(systolicpressuresValue + "");
                list.add(diastolicpressuresValue + "");
                list.add(heartValue + "");

                for (String s : list) {
                    if (s == null) return;
                }

                brocastIntent.putStringArrayListExtra(Constant.WRISTBAND_DATA, list);
                App.mContext.sendBroadcast(brocastIntent);
                break;
            case 7:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_SLEEP_CHANGED);

                ArrayList<String> valueList = new ArrayList<>();
                valueList.add(String.valueOf(values[0]));
                valueList.add(String.valueOf(values[1]));
                valueList.add(String.valueOf(values[2]));
                valueList.add(String.valueOf(values[3]));

                for (String s : valueList) {
                    if (s == null) return;
                }

                brocastIntent.putStringArrayListExtra(Constant.WRISTBAND_DATA, valueList);
                App.mContext.sendBroadcast(brocastIntent);
            default:
                break;
        }
    }

    @Override
    public void sendServiceBrocast(int type, int[] values) {
        Intent brocastIntent = new Intent(Constant.PACKAGENAME);
        switch (type) {
            case 7:
                brocastIntent.putExtra(Constant.TAG, WristBandReceiver.NOTIFY_SLEEP_CHANGED);

                ArrayList<String> valueList = new ArrayList<>();
                for (int i=0; i<values.length; i++) {
                    valueList.add(String.valueOf(values[i]));
                }

                for (String s : valueList) {
                    if (s == null) return;
                }

                brocastIntent.putStringArrayListExtra(Constant.WRISTBAND_DATA, valueList);
                App.mContext.sendBroadcast(brocastIntent);
            default:
                break;
        }
    }
    @Override
    public void scan() {
        mBleManager.scan();
    }

    @Override
    public void cancelScan() {
        mBleManager.scanCancel();
    }

    @Override
    public void connect(BluetoothDevice bluetoothDevice, BluetoothGattCallback mGattCallback) {
        mBleManager.conn(bluetoothDevice, mGattCallback);
    }

    // TODO: 2017/12/25  该方式为临时方式
    @Override
    public void setGatt(BluetoothGatt mConnGatt) {
        this.mWristbandManager = new WristbandManager(mConnGatt);
    }

    @Override
    public boolean isConnected(String mModel) {
        WristBandSettingModule module = Contas.getObject(App.mContext, WristBandSettingModule.class);
        if (module == null) return false;

        WristBandSettingModule.DataBean data = module.getData();
        if (data == null) return false;

        List<WristBandSettingModule.DataBean.ListBean> list = data.getList();
        if (list == null) return false;

        for (int i = 0; i < list.size(); i++) {
            WristBandSettingModule.DataBean.ListBean listBean = list.get(i);
            if (mModel.equals(listBean.getMac())) {
                return false;
            }
        }

        return true;
    }

    @Override
    public void correctTime() {
        mWristbandManager.setTime();
    }

    @Override
    public void readStep() {
        mWristbandManager.readStep();
    }

    @Override
    public void notifyStep() {
        mWristbandManager.notifyStep();
    }

    @Override
    public void notifyHeart() {
        mWristbandManager.notifyHeart();
    }

    @Override
    public void startHeart() {
        mWristbandManager.startHeart();
    }

    @Override
    public void notifyBlood() {
        mWristbandManager.notifyBlood();
    }

    @Override
    public void startBlood() {
        mWristbandManager.startBlood();
    }

    @Override
    public int calcStep(byte[] value) {
        if (value.length <= 4) return -1;

        int[] steps = new int[4];
        steps[0] = value[3];
        steps[1] = value[2];
        steps[2] = value[1];
        steps[3] = value[0];

        return mWristbandManager.calcStep(steps);
    }

    @Override
    public List<List<Byte>> dataReconstitution(List<byte[]> value) {
        return WristbandManager.dataReconstitution(value);
    }

    @Override
    public void readPassStepAndSleep() {
        mWristbandManager.readPassStepAndSleep();
    }

    @Override
    public void getPassStaticHeart() {
        mWristbandManager.getPassStaticHeart();
    }

    @Override
    public void notifyFatigue() {
        mWristbandManager.nofifyFatigue();
    }

    @Override
    public void readFatifue() {
        mWristbandManager.readSportState();
    }

    @Override
    public void writeUserinfo() {
        int height = 170;
        int weight = 60;
        int gender = 1;

        LoginModel.DataBean data = Contas.getObject(App.mContext, LoginModel.DataBean.class);
        if (data != null) {
            String userHei = data.getHeight();
            if (userHei != null&&userHei.length()>0)
                height = Integer.parseInt(userHei);

            String userWei = data.getWeight();
            if (!userWei.isEmpty()&&userWei.length()>0)
                weight = Integer.parseInt(userWei);

            String userGender = data.getSex();
            if (!userGender.isEmpty()&&userGender.length()>0)
                gender = Integer.parseInt(userGender);

        }

        mWristbandManager.writeUserInfo(height, weight, gender);

    }

    @Override
    public void readwristBandInfo(int type) {
        mWristbandManager.getBleInfo(type);
    }

    @Override
    public void postWristBandInfo(String mManufacturer, String mModel, String mSerial, String mHardware, String mSoftware) {

        LoginModel.DataBean userInfo = Contas.getObject(App.mContext, LoginModel.DataBean.class);
        if (userInfo == null) return;

        String uid = userInfo.getId();
        String token = userInfo.getAndroidtoken();
        if (uid == null) return;
        if (token == null) return;


        Call<BaseResp> call = ApiHelper.postWristBandInfo(mManufacturer, mModel, mSerial, mHardware, mSoftware, uid, token);
        call.enqueue(new Callback<BaseResp>() {
            @Override
            public void onResponse(Call<BaseResp> call, Response<BaseResp> response) {
                if (response != null)
                    if (response.body() != null)
                        if (response.body().getMsg() != null)
                            Log.d(TAG, response.body().getMsg());
            }

            @Override
            public void onFailure(Call<BaseResp> call, Throwable t) {
                Log.e(TAG, t.toString());
            }
        });
    }

    @Override
    public void postStepAndSleepData(List<SleepTimeModule> sleeps, List<StepPassDataModule> steps) {

        JSONObject jsonObject = new JSONObject();

        //step
        JSONArray walkArray = new JSONArray();
        for (StepPassDataModule module : steps) {
            JSONObject walk = new JSONObject();
            try {
                walk.put("time", module.getRecordTime());
                walk.put("sport_time", module.getSportTotalTime());
                walk.put("step_total", module.getTotalStep());
                List<String> stepParam = WristbandManager.getStepParam(Integer.parseInt(module.getTotalStep()));
                if (stepParam.get(1) != null)
                    walk.put("calorie", stepParam.get(1));
                else
                    walk.put("calorie", 0);

                if (stepParam.get(2) != null)
                    walk.put("odo", stepParam.get(2));
                else
                    walk.put("odo", 0);

                JSONArray hourDatas = new JSONArray();
                for (String hours : module.getHourStep()) {
                    hourDatas.put(hours);
                }
                walk.put("hour_data", hourDatas);
            } catch (JSONException e) {
                Log.d(TAG, e.toString());
            }

            walkArray.put(walk);
        }

        //sleep
        JSONArray sleepArray = new JSONArray();
        for (SleepTimeModule module : sleeps) {
            JSONObject sleep = new JSONObject();
            try {
                sleep.put("start_time", module.getStartSleepTime());
                sleep.put("end_time", module.getEndSleepTime());
                sleep.put("awake_time", module.getAwakTime());
                sleep.put("light_sleep", module.getLightSleepTime());
                sleep.put("deep_sleep", module.getDeepSleepTime());
                int sleepTotalTiem = (Integer.parseInt(module.getEndSleepTime()) - Integer.parseInt(module.getStartSleepTime())) / 60;
                sleep.put("total_sleep", sleepTotalTiem + "");

                JSONArray hourDatas = new JSONArray();
                for (String hours : module.getHoursData()) {
                    hourDatas.put(hours);
                }
                sleep.put("hour_data", hourDatas);

            } catch (JSONException e) {
                Log.d(TAG, e.toString());
            }
            sleepArray.put(sleep);
        }

        try {
            jsonObject.put("walk", walkArray);
            jsonObject.put("sleep", sleepArray);
        } catch (JSONException e) {
            Log.d(TAG, e.toString());
        }

        LoginModel.DataBean userInfoModel = Contas.getObject(App.mContext, LoginModel.DataBean.class);
        if (userInfoModel == null) return;
        String id = userInfoModel.getId();
        String androidtoken = userInfoModel.getAndroidtoken();
        if (id == null || androidtoken == null) return;
        try {
            Call<BaseResp> call = ApiHelper.postSleepAndWorkData(id, jsonObject.toString(), androidtoken);
            Log.d(TAG, jsonObject.toString());
            call.enqueue(new Callback<BaseResp>() {
                @Override
                public void onResponse(Call<BaseResp> call, Response<BaseResp> response) {
                    BaseResp body = response.body();
                    if (body != null) {
                        String msg = body.getMsg();
                        if (msg != null) {
                            Log.d(TAG, msg);
                        }
                    }
                }

                @Override
                public void onFailure(Call<BaseResp> call, Throwable t) {
                    Log.e(TAG, t.toString());
                }
            });
        } catch (Exception e) {
            Log.d(TAG, e.toString());
        }


    }

    @Override
    public void postBloodAndHeartData(ArrayList<BloodHeartPastModule> bloodHeartPastModules) {

        JSONArray jsonArray = new JSONArray();
        for (BloodHeartPastModule module : bloodHeartPastModules) {
            JSONObject data = new JSONObject();
            try {
                data.put("shousuoya", module.getCheckSbp());
                data.put("shuzhangya", module.getCheckDbp());
                data.put("xinlv", module.getCheckHeart());
                data.put("date", module.getCheckDate());
                data.put("time", module.getCheckTime());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(data);
        }

        LoginModel.DataBean userInfoData = Contas.getObject(App.mContext, LoginModel.DataBean.class);
        if (userInfoData == null) return;
        if (userInfoData.getId() == null || userInfoData.getAndroidtoken() == null) return;

        Log.d(TAG, jsonArray.toString());
        Call<BaseResp> call = ApiHelper.postBloodAndHeartData(userInfoData.getId(), jsonArray.toString(), userInfoData.getAndroidtoken());
        call.enqueue(new Callback<BaseResp>() {
            @Override
            public void onResponse(Call<BaseResp> call, Response<BaseResp> response) {
                BaseResp body = response.body();

                if (body == null) return;
                if (body.getMsg() == null) return;

                Log.d(TAG, body.getMsg());
            }
            @Override
            public void onFailure(Call<BaseResp> call, Throwable t) {
                Log.e(TAG, t.toString());
            }
        });
    }

}
